package com.scx.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.scx.util.DBConfig;


public class MysqlBaseDao {
	public final static String DRIVER = DBConfig.getInstance().getProperty("jdbc.driverClassName");
	public final static String URL = DBConfig.getInstance().getProperty("jdbc.url");
	public final static String USER = DBConfig.getInstance().getProperty("jdbc.username");
	public final static String PASS = DBConfig.getInstance().getProperty("jdbc.password");
	
	private Connection con;
	private Statement stm;
	private PreparedStatement pstm;
	private ResultSet rs;

	/*
	 * 打开数据库连接
	 */
	public void open() throws Exception {
		Class.forName(DRIVER).newInstance();
        this.con = DriverManager.getConnection(URL,USER,PASS);
	}
	
	/*
	 * 关闭数据库连接
	 */
	public void close() {
		if (this.rs != null) {
			try {
				this.rs.close();
			} catch (SQLException e) {
				//e.printStackTrace();
			}
		}
		if (this.pstm != null) {
			try {
				this.pstm.close();
			} catch (SQLException e) {
				//e.printStackTrace();
			}
		}
		if (this.stm != null) {
			try {
				this.stm.close();
			} catch (SQLException e) {
				//e.printStackTrace();
			}
		}
		if (this.con != null) {
			try {
				this.con.close();
			} catch (SQLException e) {
				//e.printStackTrace();
			}
		}
	}
	
	/**
	 * Statement 增，删，改
	 */
	public int execSQL(String sql) throws SQLException {
		this.stm = this.con.createStatement();
		return this.stm.executeUpdate(sql);
	}

	/**
	 * Statement 查
	 */
	public ResultSet findSql(String sql) throws SQLException {
		this.stm = this.con.createStatement();
		this.rs = this.stm.executeQuery(sql);
		return rs;
	}

	/**
	 * prepareStatement 增，删，改
	 */
	public int execSQL(String sql, List<String> par) throws SQLException {
		this.pstm = this.con.prepareStatement(sql);
		if (null != par) {
			for (int i = 0; i < par.size(); i++) {
				this.pstm.setString(i + 1, par.get(i) != null ? par.get(i).toString() : "");
			}
		}
		return this.pstm.executeUpdate();
	}

	/**
	 * prepareStatement 查
	 */
	public ResultSet findSql(String sql, List<String> par) throws SQLException {
		this.pstm = this.con.prepareStatement(sql);
		if (null != par) {
			for (int i = 0; i < par.size(); i++) {
				this.pstm.setString(i + 1, par.get(i).toString());
			}
		}
		this.rs = this.pstm.executeQuery();
		return this.rs;
	}
	

}
